package redis

import (
	"crypto/sha256"
	"eci-forward/pkg/config"
	"eci-forward/pkg/logs"
	"encoding/hex"
	"sort"
	"strings"

	"github.com/go-redis/redis/v8"
	"go.uber.org/zap"
)

var client *redis.Client
var Nil = redis.Nil

// var SetNX = client.SetNX
// var Get = client.Get
// var Set = client.Set

func Init() {
	client = redis.NewClient(&redis.Options{
		Addr:     config.GetBasicConfig().RedisAddr,
		Username: config.GetBasicConfig().RedisUsername,
		Password: config.GetBasicConfig().RedisPassword,
		DB:       config.GetBasicConfig().RedisDB,
	})
	res, err := client.Ping(client.Context()).Result()
	if err != nil {
		logs.Logger.Error("redis connect failed", zap.String("res", res), zap.Error(err))
	}
}

func GetClient() *redis.Client {
	return client
}
func generateShortKey(rawKey string) string {
	hasher := sha256.New()
	hasher.Write([]byte(rawKey))
	hashBytes := hasher.Sum(nil)
	shortKey := hex.EncodeToString(hashBytes)
	return shortKey
}

func BuildRedisKey(departmentName string, images []string) string {
	sort.Strings(images)

	rawKey := "image_cache:" + departmentName + ":" + strings.Join(images, ",")
	return generateShortKey(rawKey)
}
